
home = File.expand_path(File.dirname(__FILE__))
$LOAD_PATH.unshift(home) unless $LOAD_PATH.include?(home)
assembly_home = File.join(home, 'piston/assembly')
$LOAD_PATH.unshift(assembly_home) unless $LOAD_PATH.include?(assembly_home)

require 'piston/version'
require 'piston/config'
require 'piston/plugin/core/core'

xaml_file = File.join home, 'piston/plugin/core/view/main_window.xaml'
xaml_builder = Piston::Core::XamlBuilder.new xaml_file

workspace = Piston::Workspace.instance

paths = Dir["#{home}/piston/plugin/*"]
paths.each do |path|
  name = File.basename(path)
  next if name == 'core'
  full = File.join path, name + '.rb'
  next unless File.exist? full
  plugin_loader = Piston::Core::PluginLoader.new(full)
  plugin_loader.load_plugin_module
  plugin_loader.load_plugin

  plugin = Piston::Plugin.new

  plugin.view xaml_builder
  workspace.add_commands plugin.commands
  workspace.plugins << {
    'name' => name,
    'file' => full,
    'author' => plugin.author,
    'version' => plugin.version
  }
end

xaml_content = xaml_builder.outer_xml.gsub('xmlns=""', '').gsub('pack://application:,,,', home)

temp_file = File.join home, 'view.xml'
File.open(temp_file, 'w+') { |fp|  fp.write xaml_content}

win = System::Windows::Markup::XamlReader.parse xaml_content
workspace.main_window = win
win.data_context = workspace

workspace.plugins.each do |data|
  plugin_loader = Piston::Core::PluginLoader.new(data['file'])
  plugin_loader.load_plugin_module
  plugin_loader.load_plugin

  plugin = Piston::Plugin.new
  plugin.after_build(win)
end

app = System::Windows::Application.new
app.run(win)
